﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Threading;

namespace Genesis
{
    public partial class frmimport : Form
    {
        public string[,] SongArray = new string[1, 7] { { "", "", "", "", "", "0", "0" } };
        public string tmp = "";
        List<Song> tmpsonglist = new List<Song>();

        public frmimport()
        {
            InitializeComponent();
        }
        private void frmimport_Load(object sender, EventArgs e)
        {
            FileDiag.ShowDialog();
            if (File.Exists(FileDiag.FileName))
            {
                while (Valid_Library(FileDiag.FileName) == false)
                {
                    MessageBox.Show("'" + FileDiag.FileName + "' is not a valid library. Please select a valid library.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    FileDiag.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                    FileDiag.ShowDialog();
                }
                LoadLibrary(FileDiag.FileName, Application.StartupPath + @"\tmp.dad");
                tmpsonglist = InitializeLibrary();
                pBar.Maximum = tmpsonglist.Count;
                BGWork.RunWorkerAsync(FileDiag.FileName);
            }
            else
            {
                this.DialogResult = DialogResult.Abort;
            }
        }
        private void frmimport_Closing(object sender, EventArgs e)
        {
            if (this.DialogResult != DialogResult.OK)
                this.DialogResult = DialogResult.Cancel;
        }


        public void LoadLibrary(string libPath, string tmpLib)
        {
            int count = 0;
            XmlDocument iLibrary = new XmlDocument();

            File.Copy(libPath, tmpLib, true);

            string[] oldContents = File.ReadAllLines(tmpLib);
            string[] newContents = new string[oldContents.Length - 2];
            for (int i = 2; i < oldContents.Length; i++)
                newContents[i - 2] = oldContents[i];

            File.WriteAllLines(tmpLib, newContents);

            iLibrary.Load(tmpLib);

            XmlNodeList Key = iLibrary.GetElementsByTagName("key");
            pBar.Maximum = Key.Count;
            // 0 - Name
            // 1 - Artist
            // 2 - Album
            // 3 - Genre
            // 4 - Location
            // 5 - Time
            // 6 - Count
            foreach (XmlNode node in Key)
            {
                XmlElement x = (XmlElement)node;

                if (x.InnerText == "Playlists")
                    break;
                else
                {
                    if (x.InnerText == "Kind")
                    {
                        if (x.NextSibling.InnerText == "MPEG-4 video file")
                        {
                            count--;
                            Resize_Arrays("DOWN");
                        }
                    }
                    else if (x.InnerText == "Name")
                    {
                        SongArray[count, 0] = (x.NextSibling.InnerText);
                        count++;
                        Resize_Arrays("UP");
                    }
                    else if (x.InnerText == "Artist")
                        SongArray[count - 1, 1] = (x.NextSibling.InnerText);
                    else if (x.InnerText == "Album")
                        SongArray[count - 1, 2] = (x.NextSibling.InnerText);
                    else if (x.InnerText == "Genre")
                        SongArray[count - 1, 3] = (x.NextSibling.InnerText);
                    else if (x.InnerText == "Location")
                        SongArray[count - 1, 4] = (x.NextSibling.InnerText);
                    else if (x.InnerText == "Total Time")
                        SongArray[count - 1, 5] = Convert.ToString(Convert.ToInt32(x.NextSibling.InnerText) / 1000);
                    else if (x.InnerText == "Play Count")
                        SongArray[count - 1, 6] = Convert.ToString(Convert.ToInt32(x.NextSibling.InnerText));
                }
            }

            if (SongArray[SongArray.GetLength(0) - 1, 0] == "")
                Resize_Arrays("DOWN");

            File.Delete(tmpLib);
        }
        private List<Song> InitializeLibrary()
        {
            List<Song> song = new List<Song>();

            for (int i = 0; i < SongArray.GetLength(0); i++)
                song.Add(new Song(SongArray[i, 0], SongArray[i, 1], SongArray[i, 2], SongArray[i, 3], SongArray[i, 5], Convert.ToInt32(SongArray[i, 6]), SongArray[i, 4], DateTime.UtcNow));

            // Remove String Mutations [ -> %5d...yuck!
            foreach (Song s in song)
                s.Location = Uri.UnescapeDataString(s.Location);

            return song;
        }
        private void Resize_Arrays(string Direction)
        {
            string[,] oldSong = new string[SongArray.GetLength(0), 7];

            if (Direction == "UP")
            {
                for (int i = 0; i < SongArray.GetLength(0); i++)
                {
                    oldSong[i, 0] = SongArray[i, 0];
                    oldSong[i, 1] = SongArray[i, 1];
                    oldSong[i, 2] = SongArray[i, 2];
                    oldSong[i, 3] = SongArray[i, 3];
                    oldSong[i, 4] = SongArray[i, 4];
                    oldSong[i, 5] = SongArray[i, 5];
                    oldSong[i, 6] = SongArray[i, 6];
                }
                SongArray = new string[SongArray.GetLength(0) + 1, 7];
                for (int i = 0; i < oldSong.GetLength(0); i++)
                {
                    SongArray[i, 0] = oldSong[i, 0];
                    SongArray[i, 1] = oldSong[i, 1];
                    SongArray[i, 2] = oldSong[i, 2];
                    SongArray[i, 3] = oldSong[i, 3];
                    SongArray[i, 4] = oldSong[i, 4];
                    SongArray[i, 5] = oldSong[i, 5];
                    SongArray[i, 6] = oldSong[i, 6];
                }
                SongArray[SongArray.GetLength(0) - 1, 0] = "";
                SongArray[SongArray.GetLength(0) - 1, 1] = "";
                SongArray[SongArray.GetLength(0) - 1, 2] = "";
                SongArray[SongArray.GetLength(0) - 1, 3] = "";
                SongArray[SongArray.GetLength(0) - 1, 4] = "";
                SongArray[SongArray.GetLength(0) - 1, 5] = "0";
                SongArray[SongArray.GetLength(0) - 1, 6] = "0";
            }
            else
            {
                for (int i = 0; i < SongArray.GetLength(0); i++)
                {
                    oldSong[i, 0] = SongArray[i, 0];
                    oldSong[i, 1] = SongArray[i, 1];
                    oldSong[i, 2] = SongArray[i, 2];
                    oldSong[i, 3] = SongArray[i, 3];
                    oldSong[i, 4] = SongArray[i, 4];
                    oldSong[i, 5] = SongArray[i, 5];
                    oldSong[i, 6] = SongArray[i, 6];
                }
                SongArray = new string[SongArray.GetLength(0) - 1, 7];
                for (int i = 0; i < SongArray.GetLength(0); i++)
                {
                    SongArray[i, 0] = oldSong[i, 0];
                    SongArray[i, 1] = oldSong[i, 1];
                    SongArray[i, 2] = oldSong[i, 2];
                    SongArray[i, 3] = oldSong[i, 3];
                    SongArray[i, 4] = oldSong[i, 4];
                    SongArray[i, 5] = oldSong[i, 5];
                    SongArray[i, 6] = oldSong[i, 6];
                }
            }
        }
        private bool Valid_Library(string path)
        {
            try
            {
                string[] lines = File.ReadAllLines(path);
                if (lines[1].Contains("http://www.apple.com/DTDs/PropertyLis") == true)
                    return true;
                else
                    return false;
            }
            catch { return false; }

        }

        private void BGWork_DoWork(object sender, DoWorkEventArgs e)
        {
            List<Song> lib = InitializeLibrary();
            for (int i = 0; i < lib.Count; i++)
            {
                Library.AddSong(lib[i]);
                BGWork.ReportProgress(i);
            }
        }
        private void BGWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pBar.Value = e.ProgressPercentage;
            lblStatus.Text = ("Adding: " + tmpsonglist[e.ProgressPercentage].Title);
        }
        private void BGWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
    }
}
